/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package koor.action.student;

import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import koor.action.Action;
import koor.action.ActionResult;
import koor.entity.Student;
import koor.persistent.StudentDAO;
import koor.service.ServiceLocator;

/**
 * The
 * <code>StudentAction</code> class represents action, used to view student
 * information
 *
 * @author Admin
 */
public class StudentAction implements Action {

    @Override
    public String getName() {
        return "student.view";
    }

    @Override
    public ActionResult execute(HttpServletRequest request, HttpServletResponse response) {
        StudentDAO studentDAO = ServiceLocator.getService(StudentDAO.class);

        if ((request.getParameter("id") != null) || (request.getSession().getAttribute("id") != null)) {
            try {
                Long id = (request.getParameter("id") != null) ? (Long.parseLong(request.getParameter("id"))) : ((Integer) request.getSession().getAttribute("id"));
                Student student = studentDAO.findOne(id);
                request.setAttribute("student", student);
                return ActionResult.forward("StudentView/StudentView.jsp");
            } catch (NumberFormatException e) {
                request.setAttribute("fail", "Неверный номер");
            } catch (RuntimeException e) {
                request.setAttribute("fail", "Студент не найден");
            }
        }

        List<Student> studentList = studentDAO.findAll();
        request.setAttribute("studentList", studentList);
        return ActionResult.forward("StudentView/StudentListView.jsp");
    }
}
